import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3000'
axios.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    // 如果 token 存在，在每个 HTTP header 都加上 token
    // Bearer 是 JWT 的认证头部信息
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
class Request {
  constructor({ username, password, type }) {
    this.username = username
    this.password = password
    this.type = type
  }
  /* 注册 */
  async register() {
    const res = await axios.post('/api/register', {
      username: this.username,
      password: this.password,
      type: this.type
    })
    return res
  }
  /* 登录 */
  async login() {
    const res = await axios.post('/api/login', {
      username: this.username,
      password: this.password,
      type: this.type
    })
    //将token设置到localStorage中
    if (res.data.token) {
      localStorage.setItem('token', res.data.token)
    }
    return res
  }
  /* 注销 */
  async logout(flag) {
    const res = await axios.post('/api/logout', {
      username: this.username,
      type: this.type
    })
    if (flag) {
      localStorage.removeItem('token')
    }
    return res
  }
  /*修改密码*/
  async update(newPassword) {
    const res = await axios.post('/api/update', {
      username: this.username,
      type: this.type,
      oldPassword: this.password,
      newPassword
    })
    return res
  }
  /* 修改用户信息 */
  async change(username, type, password, id) {
    console.log("change", username, type, password, id);
    const res = await axios.post('/api/change', {
      username,
      type,
      password,
      id
    })
    return res
  }
  /* 删除用户 */
  async delete(username, type) {
    const res = await axios.post('/api/delete', {
      username,
      type
    })
    return res
  }
  /* 获取用户信息 */
  async getUser(type) {
    try {
      const res = await axios.get(`/api/user?type=${type}`)
      return res
    } catch (err) {
      console.log(err)
    }
  }
}
export default Request
